<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="96px">
    <el-form-item label="区域" prop="region_id">
      <el-tree-select
        v-model="form.region_id"
        :data="regionOptions"
        placeholder="请选择区域"
        filterable
        check-strictly
        :render-after-expand="false"
        :props="treeProps"
        class="w-full"
      />
    </el-form-item>
    <el-form-item label="用户ID" prop="user_id">
      <el-input v-model="form.user_id" placeholder="请输入用户ID" />
    </el-form-item>
    <el-form-item label="角色类型" prop="role_type">
      <el-select
        v-model="form.role_type"
        placeholder="请选择角色类型"
        class="w-full"
      >
        <el-option
          v-for="item in roleOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="主负责人" prop="is_primary">
      <el-switch
        v-model="form.is_primary"
        inline-prompt
        :active-value="1"
        :inactive-value="0"
        active-text="是"
        inactive-text="否"
      />
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-radio-group v-model="form.status">
        <el-radio :label="1">启用</el-radio>
        <el-radio :label="0">禁用</el-radio>
      </el-radio-group>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  createRegionUser,
  updateRegionUser,
  fetchRegionUserDetail,
  REGION_USER_ROLE_OPTIONS
} from "@/api/system/region/region";

interface RegionOption {
  id: number;
  name: string;
  children?: RegionOption[];
}

const treeProps = {
  label: "name",
  value: "id",
  children: "children"
};

const props = defineProps<{
  id?: number | null;
  regionOptions: RegionOption[];
}>();

const emit = defineEmits<{ (e: "success"): void }>();

const formRef = ref();

const form = reactive({
  region_id: props.id ? 0 : undefined,
  user_id: "",
  role_type: REGION_USER_ROLE_OPTIONS[0]?.value ?? "operator",
  is_primary: 0,
  status: 1
});

const rules = {
  region_id: [{ required: true, message: "请选择区域", trigger: "change" }],
  user_id: [
    {
      required: true,
      message: "请输入用户ID",
      trigger: "blur"
    },
    {
      validator: (_: any, value: string, callback: Function) => {
        if (!value) return callback(new Error("请输入用户ID"));
        if (!/^\d+$/.test(value.trim())) {
          callback(new Error("用户ID必须为数字"));
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ]
};

const roleOptions = REGION_USER_ROLE_OPTIONS;

const loadDetail = async (id: number) => {
  try {
    const detail = await fetchRegionUserDetail(id);
    form.region_id = detail.region_id;
    form.user_id = String(detail.user_id);
    form.role_type = detail.role_type ?? roleOptions[0]?.value ?? "operator";
    form.is_primary = detail.is_primary ?? 0;
    form.status = detail.status ?? 1;
  } catch (error: any) {
    ElMessage.error(error?.message ?? "加载详情失败");
  }
};

watch(
  () => props.id,
  newId => {
    if (newId) {
      loadDetail(newId);
    } else {
      form.region_id = undefined;
      form.user_id = "";
      form.role_type = roleOptions[0]?.value ?? "operator";
      form.is_primary = 0;
      form.status = 1;
    }
  },
  { immediate: true }
);

const submitForm = async () => {
  const formEl = formRef.value as any;
  if (!formEl) return false;
  const valid = await formEl.validate().catch(() => false);
  if (!valid) return false;

  const payload = {
    region_id: Number(form.region_id),
    user_id: Number(form.user_id),
    role_type: form.role_type,
    is_primary: form.is_primary,
    status: form.status
  };

  try {
    if (props.id) {
      await updateRegionUser(props.id, payload);
      ElMessage.success("区域成员已更新");
    } else {
      await createRegionUser(payload);
      ElMessage.success("区域成员已添加");
    }
    emit("success");
    return true;
  } catch (error: any) {
    ElMessage.error(error?.message ?? "提交失败");
    return false;
  }
};

defineExpose({
  submitForm
});
</script>
